/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package JPAControllers;

import JPAControllers.exceptions.IllegalOrphanException;
import JPAControllers.exceptions.NonexistentEntityException;
import Persistencia.Paciente;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Persistencia.Sesion;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author veinti
 */
public class PacienteJpaController {

    public PacienteJpaController() {
        emf = Persistence.createEntityManagerFactory("fisiosoftJDVPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Paciente paciente) {
        if (paciente.getSesionList() == null) {
            paciente.setSesionList(new ArrayList<Sesion>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Sesion> attachedSesionList = new ArrayList<Sesion>();
            for (Sesion sesionListSesionToAttach : paciente.getSesionList()) {
                sesionListSesionToAttach = em.getReference(sesionListSesionToAttach.getClass(), sesionListSesionToAttach.getIdSesion());
                attachedSesionList.add(sesionListSesionToAttach);
            }
            paciente.setSesionList(attachedSesionList);
            em.persist(paciente);
            for (Sesion sesionListSesion : paciente.getSesionList()) {
                Paciente oldPacienteOfSesionListSesion = sesionListSesion.getPaciente();
                sesionListSesion.setPaciente(paciente);
                sesionListSesion = em.merge(sesionListSesion);
                if (oldPacienteOfSesionListSesion != null) {
                    oldPacienteOfSesionListSesion.getSesionList().remove(sesionListSesion);
                    oldPacienteOfSesionListSesion = em.merge(oldPacienteOfSesionListSesion);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Paciente paciente) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Paciente persistentPaciente = em.find(Paciente.class, paciente.getIdPaciente());
            List<Sesion> sesionListOld = persistentPaciente.getSesionList();
            List<Sesion> sesionListNew = paciente.getSesionList();
            List<String> illegalOrphanMessages = null;
            for (Sesion sesionListOldSesion : sesionListOld) {
                if (!sesionListNew.contains(sesionListOldSesion)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Sesion " + sesionListOldSesion + " since its paciente field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Sesion> attachedSesionListNew = new ArrayList<Sesion>();
            for (Sesion sesionListNewSesionToAttach : sesionListNew) {
                sesionListNewSesionToAttach = em.getReference(sesionListNewSesionToAttach.getClass(), sesionListNewSesionToAttach.getIdSesion());
                attachedSesionListNew.add(sesionListNewSesionToAttach);
            }
            sesionListNew = attachedSesionListNew;
            paciente.setSesionList(sesionListNew);
            paciente = em.merge(paciente);
            for (Sesion sesionListNewSesion : sesionListNew) {
                if (!sesionListOld.contains(sesionListNewSesion)) {
                    Paciente oldPacienteOfSesionListNewSesion = sesionListNewSesion.getPaciente();
                    sesionListNewSesion.setPaciente(paciente);
                    sesionListNewSesion = em.merge(sesionListNewSesion);
                    if (oldPacienteOfSesionListNewSesion != null && !oldPacienteOfSesionListNewSesion.equals(paciente)) {
                        oldPacienteOfSesionListNewSesion.getSesionList().remove(sesionListNewSesion);
                        oldPacienteOfSesionListNewSesion = em.merge(oldPacienteOfSesionListNewSesion);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = paciente.getIdPaciente();
                if (findPaciente(id) == null) {
                    throw new NonexistentEntityException("The paciente with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Paciente paciente;
            try {
                paciente = em.getReference(Paciente.class, id);
                paciente.getIdPaciente();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The paciente with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Sesion> sesionListOrphanCheck = paciente.getSesionList();
            for (Sesion sesionListOrphanCheckSesion : sesionListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Paciente (" + paciente + ") cannot be destroyed since the Sesion " + sesionListOrphanCheckSesion + " in its sesionList field has a non-nullable paciente field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(paciente);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Paciente> findPacienteEntities() {
        return findPacienteEntities(true, -1, -1);
    }

    public List<Paciente> findPacienteEntities(int maxResults, int firstResult) {
        return findPacienteEntities(false, maxResults, firstResult);
    }

    private List<Paciente> findPacienteEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Paciente.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Paciente findPaciente(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Paciente.class, id);
        } finally {
            em.close();
        }
    }

    public int getPacienteCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Paciente> rt = cq.from(Paciente.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
